package cn.bdqn.service;

import cn.bdqn.mapper.ItemKillMapper;
import cn.bdqn.mapper.ItemKillSuccessMapper;
import cn.bdqn.pojo.ItemKill;
import cn.bdqn.pojo.ItemKillSuccess;
import cn.bdqn.vo.EmailDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.annotation.RabbitListeners;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * RabbitMQ消费者服务
 */
@Service
public class RabbitMQConsumerService {

    private static final Logger log = LoggerFactory.getLogger(RabbitMQConsumerService.class);

    @Resource
    private EmailService emailService;
    @Resource
    private ItemKillSuccessMapper itemKillSuccessMapper;
    @Resource
    private ItemKillMapper itemKillMapper;

    /**
     * 邮件队列消费者
     */
    @RabbitListener(queues = {"${mq.kill.success.email.queue}"})
    public void emailQueueConsumer(EmailDto emailDto){
        System.out.println("邮件队列消费者，消费的消息是："+emailDto);
        System.out.println("开始调用邮件服务，发送邮件....");
        String content = new StringBuilder().append("恭喜你，").append(emailDto.getItemName()).append("秒杀成功，订单号是：").append(emailDto.getCode()).append("，当前订单状态：").append(emailDto.getStatus()==0?"未付款，请在30分钟内完成付款："+emailDto.getPayAddress():"已付款，等待收货").toString();
        System.out.println(content);
        emailService.sending(emailDto.getEmail(),"科泰商城",content);
    }

    /**
     * 真正队列消费者
     * @param code 订单号
     */
    @RabbitListener(queues = {"${mq.kill.success.dead.base.queue}"})
    public void deadBaseQueueConsumer(String code){
        System.out.println("----------------"+code);
        //判断当前订单号是否为空
        if(code != null && !"".equals(code)){
            //查询当前这个订单的状态
            ItemKillSuccess itemKillSuccess = itemKillSuccessMapper.selectById(code);
            System.out.println("=================="+itemKillSuccess);
            //判断当前订单的支付状态
            if(itemKillSuccess.getStatus() == 0){
                //订单还未支付，让订单失效
                ItemKillSuccess ik = new ItemKillSuccess();
                ik.setCode(code);
                ik.setStatus(-1);
                int row = itemKillSuccessMapper.updateById(ik);
                log.info("订单号：{}，已经失效！",code);
                if(row>0){
                    //订单失效，对应商品的库存+1
                    itemKillMapper.updateByIdAdd(itemKillSuccess.getKillId());
                }
            }
        }
    }
}
